import { loginAPI } from '@/api/user';
import { LoginParams, UserInfoData, UserLoginResponseData } from './../../api/user/type';
import { defineStore } from "pinia";
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

const useUserStore = defineStore('user', () => {
    const visible = ref<boolean>(false)
    const userInfo = ref<UserInfoData>({} as UserInfoData)
    let $router = useRouter()

    const login = async (loginForm: LoginParams) => {
        let res: UserLoginResponseData = await loginAPI(loginForm)
        if (res.code == 200) {
            userInfo.value = res.data
            return 'ok'
        } else {
            return Promise.reject(new Error(res.message))
        }
    }

    const logout = () => {
        ElMessageBox.confirm(
            '确定要退出登录吗?',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                userInfo.value = { name: '', token: "" }
                $router.push('/')
                ElMessage({
                    type: 'success',
                    message: "退出登录成功！"
                })
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消成功',
                })
            })
    }

    const changeVisible = () => {
        let timer = setInterval(() => {
            let user = JSON.parse((localStorage.getItem('user') as string))
            if (user?.userInfo.name) {
                visible.value = false
                clearInterval(timer)
            }
        }, 1000)
    }

    return {
        visible, userInfo, login, logout, changeVisible
    }
}, {
    persist: true
})

export default useUserStore